package com.example.shopdemo.utils;

import com.example.shopdemo.entity.PersonInfo;
import com.example.shopdemo.entity.UserAccessToken;
import com.example.shopdemo.entity.WeiXinUser;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.*;
import java.net.ConnectException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;

/**
 * @author ：Anitaxiaofeng
 * @description：
 * @create 2018-02-04
 **/
@Slf4j
public class WeiXinUserUtil {



    public static UserAccessToken getUserAccessToken(String code) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
        //TODO 重配置文件中读取
        String appId = "appid";
        String appsecret = "appsecret";
        //根据传入的code，拼接出访问微信定义好的接口url
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
                + appId + "&secret=" + appsecret + "&code=" + code
                + "&grant_type=authorization_code";
        //向相应URL发送请求获取token json字符串
        String tokenStr = httpsRequest(url,"GET",null);
        log.debug("userAccessTokenStr:{}",tokenStr);
        UserAccessToken token = new UserAccessToken();
        ObjectMapper objectMapper = new ObjectMapper();
        try{
            //将json字符串转换成相应对象
            token = objectMapper.readValue(tokenStr,UserAccessToken.class);
        }catch(JsonParseException e){
            log.error("获取用户access_token失败:{}",e.getMessage());
        }catch(JsonMappingException e){
            log.error("获取用户access_token失败:{}",e.getMessage());
        }catch(IOException e){
            log.error("获取用户access_token失败:{}",e.getMessage());
        }
        if(token==null){
            log.error("获取用户access_token失败");
            return null;
        }
        return token;

    }


    public static WeiXinUser getUserInfo(String accessToken,String openId) throws NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
        //根据传入的accessToken和openId拼接出访问微信定义的端口并获取用户信息的Url
        String url = "https://api.weixin.qq.com/sns/userinfo?access_token="
                + accessToken + "&openid=" + openId + "&lang=zh_CN";
        String userStr = httpsRequest(url,"GET",null);
        WeiXinUser user = new WeiXinUser();
        ObjectMapper objectMapper = new ObjectMapper();
        try{
            //将json字符串转换成相应对象
            user = objectMapper.readValue(userStr,WeiXinUser.class);
        }catch(JsonParseException e){
            log.error("获取用户信息失败:{}",e.getMessage());
        }catch(JsonMappingException e){
            log.error("获取用户信息失败:{}",e.getMessage());
        }catch(IOException e){
            log.error("获取用户信息失败:{}",e.getMessage());
        }
        if(user ==null){
            log.error("获取用户信息失败");
            return null;
        }
        return user;
    }

    /**
     * 发送https请求并获取结果
     * @param requestUrl
     * @param requestMethod
     * @param outputStr 提交的数据
     * @return json字符串
     */
    public static String httpsRequest(String requestUrl,String requestMethod,String outputStr) throws NoSuchProviderException, NoSuchAlgorithmException, KeyManagementException {
        StringBuffer buffer = new StringBuffer();
        try {
            // 创建SSLContext对象，并使用我们指定的信任管理器初始化
            TrustManager[] tm = { new MyX509TrustManager() };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(requestUrl);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
            httpUrlConn.setSSLSocketFactory(ssf);

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            httpUrlConn.setRequestMethod(requestMethod);

            if ("GET".equalsIgnoreCase(requestMethod))
                httpUrlConn.connect();

            // 当有数据需要提交时
            if (null != outputStr) {
                OutputStream outputStream = httpUrlConn.getOutputStream();
                // 注意编码格式，防止中文乱码
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }

            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
            log.debug("https buffer:"+buffer.toString());
        } catch (ConnectException ce) {
            log.error("Weixin server connection timed out.");
        } catch (Exception e) {
            log.error("https request error:{}", e);
        }
        return buffer.toString();

    }


    /**
     * 将user里的信息转换成PersonInfo信息
     * @param weiXinUser
     * @return
     */
    public static PersonInfo getPersonInfoFromRequest(WeiXinUser weiXinUser){
        PersonInfo personInfo = new PersonInfo();
        personInfo.setName(weiXinUser.getNickName());
        personInfo.setGender(weiXinUser.getSex());
        personInfo.setProfileImg(weiXinUser.getHeadimgurl());
        personInfo.setEnableStatus(1);
        return personInfo;
    }
}




